/**
 * @Desc this class is packed for grid pagination based on jquery
 * @Param default parameters,for request url,parameter,callback invoking
 * @Author daizhehua
 * @Date 2015/11/14
 */

function SmartPage(settings){
	this.maskId = settings.maskId || "wd-table";
	this.pageWrap = settings.node;
	this.langPath = settings.langPath || "js/common/smartPage/";
	this.count = settings.count || 10;
	this.url = settings.url;
	this.req = {
		currPage : 1,	
		pageSize : this.count
    };
	$.extend(this.req,settings.data ||{});
	this.callback = settings.callback;
	this.type = settings.type;
	this.avoid = false;
	this.pageList = [10,20,50];
	this.token = true;
	this.init();
}

SmartPage.prototype = {
		init:function(){
			var _page = this;
			_page.pageDiv = $("<div class=\"czdivbox\"></div>");
			_page.pageWrap.html("");
			_page.pageWrap.append(_page.pageDiv);
		    jQuery.i18n.properties({
		        name: "page",
		        path: _page.langPath,
		        mode: 'map',
		        language: _page.getCookie("language"),
		        callback: function () {
		        	_page.langMap = $.i18n.map;
		        }
		    });
		    _page.ajaxGet(function(){
				_page.setLinks();
				_page.bindLinks();
			});
		},
		//获取cookie
		getCookie: function(objName){
			var arrStr = document.cookie.split("; ");
			for(var i = 0;i < arrStr.length;i ++){
				var temp = arrStr[i].split("=");
				if(temp[0] == objName){
					return unescape(temp[1]);
					}
				}
		},
		search:function(url,data){
			var _page = this;
			_page.pageWrap.html('');
			_page.url = url;
			_page.req = {
				currPage : 1,	
				pageSize : _page.count
		    };
			$.extend(_page.req,data ||{});
			_page.init();
		},
		reload:function(){
			var _page = this;
			_page.ajaxGet(_page.setLinks);
		},
		top:function(){
			var _page = this;
			var _topBtn = $(_page.pageDiv.find(".topPage")[0]);
			if(_topBtn.hasClass("div_fleft_all"))
				return;
			_page.req.currPage = 1;
			_page.req.pageSize = _page.count;
			_page.ajaxGet(_page.setLinks);
		},
		prev:function(){
			var _page = this;
			var _prevBtn = $(_page.pageDiv.find(".prePage")[0]);
			if(_prevBtn.hasClass("div_fleft"))
				return;
			var _currPage = _page.msg.currPage;
			var _newPage = _currPage-1;
			_page.req.currPage = _newPage;
			_page.req.pageSize = _page.count;
			_page.ajaxGet(_page.setLinks);
		},
	    next:function(){
	    	var _page = this;
	    	var _nextBtn = $(_page.pageDiv.find(".nextPage")[0]);
			if(_nextBtn.hasClass("div_right"))
				return;
	    	var _currPage = _page.msg.currPage;
			var _newPage = _currPage+1;
			_page.req.currPage = _newPage;
			_page.req.pageSize = _page.count;
	    	_page.ajaxGet(_page.setLinks);
	    },
	    bottom:function(){
	    	var _page = this;
	    	var _bottomBtn = $(_page.pageDiv.find(".bottomPage")[0]);
			if(_bottomBtn.hasClass("div_rightall"))
				return;
	    	var _pageCnt = _page.msg.pageCnt; 
			_page.req.currPage = _pageCnt;
			_page.req.pageSize = _page.count;
			_page.ajaxGet(_page.setLinks);
	    },
	    changeRow:function(rowCnt){
	    	var _page = this;
	    	_page.count = rowCnt;
			_page.req.currPage = 1;
			_page.req.pageSize = _page.count;
	    	_page.ajaxGet(_page.setLinks);
	    },
		getByNum:function(n){
			var _page = this;
			_page.req.currPage = n;
			_page.req.pageSize = _page.count;
			_page.ajaxGet(_page.setLinks);
	    },
	    ajaxGet:function(func){
	    	var _page = this;
	    	var _langMap = _page.langMap;
	    	if (!_page.token) {
				return false;
			}
			_page.token = false;
	    	// 遮蔽层处理
			if (_page.height != undefined) {
				var shield = document.createElement("DIV");
				shield.id = "wd-shield";
				shield.className = "wd-shield";
				shield.style.width = $("#"+_page.maskId)[0].clientWidth + "px";
				shield.style.height = (_page.height + 40) + "px";
				shield.style.top = $("#"+_page.maskId).offset().top + "px";
				shield.style.left = $("#"+_page.maskId).offset().left + "px";
				document.body.appendChild(shield);
				
	
				var shieldText = document.createElement('span');
				shieldText.id = "wd-shieldText";
				shieldText.className = "wd-shieldText";
				shieldText.style.width = $("#"+_page.maskId)[0].clientWidth + "px";
				
				var shieldHeight = $("#"+_page.maskId)[0].clientHeight + 40;
				var shieldTop = $("#"+_page.maskId).offset().top;
				shieldText.style.top = shieldTop + (shieldHeight/2) - 30 + "px";
				
				shieldText.style.left = $("#"+_page.maskId).offset().left + "px";
				
				var tempDiv = document.createElement('div');
				shieldText.appendChild(tempDiv);
				document.body.appendChild(shieldText);
			}
			
	        if(_page.avoid) return;
	        _page.avoid = true;
	        var _apply = function(msg){
	        	_page.msg = msg;
	            if(_page.callback) _page.callback(msg.data,msg.total);
	            func.call(_page);
	            _page.avoid = false;
	        };
	        
	        switch(_page.type){
	            case "post":
				     $.ajax({ 
						 'type' : 'post',
				         'url' : _page.url,
				         'async': true,
				         'cache':false,
				         'contentType':'application/json', 
				         'data' : JSON.stringify(_page.req),
				         'dataType' : 'json',
				         beforeSend: function(){
				        	 if(!_page.height) interfaceApp.block();
				         },
				         success:function(data){  
				        	 _page.token = true;
				        	 if(typeof data != "object"){
				        		 return;
				        	 }
				        	 if (_page.height != undefined) {
			        		 	document.body.removeChild(document.getElementById("wd-shield"));
			        		 	document.body.removeChild(document.getElementById("wd-shieldText"));
				        	 }else{
				        		 //$("#"+_page.maskId)[0].removeChild(document.getElementById("wd-wite"));
				        	 }
				        	 _apply(data);    
				         },
				         complete: function(){
				        	 interfaceApp.unblock();
				         }
				     });
	                 break;
	            case "get":
	            	$.ajax({ 
						 'type' : 'get',
				         'url' : _page.url,
				         'async': true,
				         'cache':false,
				         'data' : _page.req,
				         'dataType' : 'json',
				         beforeSend: function(){
				        	 if(!_page.height) interfaceApp.block();
				         },
				         success:function(data){  
				        	 _page.token = true;
				        	 if(typeof data != "object"){
				        		 return;
				        	 }
				        	 if (_page.height != undefined) {
					        	 document.body.removeChild(document.getElementById("wd-shield"));
								 document.body.removeChild(document.getElementById("wd-shieldText"));
				        	 }
				        	 _apply(data);    
				         },
				         complete: function(){
				        	 interfaceApp.unblock();
				         }
				     });
	                 break;
	             default :
	            	 _apply({data:null,total:0,start:0,end:9,currPage:1,pageSize:_page.count,pageCnt:1});
	        };
	    },
	    setLinks : function(){	
	    	var _page = this;
	    	var _total = _page.msg.total;
	    	var _start = _page.msg.start;
	    	var _end = _page.msg.end;
	    	var _currPage = _page.msg.currPage;
	    	var _pageSize = _page.msg.pageSize;
	    	var _pageCnt = _page.msg.pageCnt;
	    	var _langMap = _page.langMap;
	    	if(_pageCnt == 0){
	    		_page.pageWrap.html("");
	    		_page.pageWrap.append("<div style=\"font-size: 12px; display: block;\">"+_langMap["i18n_page_zwsj"]+"</div>");
	    		return;
	    	}
	    	if(_currPage == _pageCnt){
	    		if(_page.msg.data){
	    			var cnt = _page.msg.data.length;
	    			_end = _start + cnt - 1;
	    		}
	    	}
	    	var html = "<div id=\"wd-tablediv_fleft_all\" class=\"czdiv div_fleft_all_active topPage\"></div>";
				html +="<div id=\"wd-tablediv_fleft\" class=\"czdiv div_fleft_active prePage\"></div>";
				html +="<div class=\"span_blank\"></div>";
				html +="<div class=\"div_span\">"+_langMap["i18n_page_d"]+"</div>";
				html +="<input type=\"text\" min=\"1\" max=\""+_pageCnt+"\" class=\"input_page\" type=\"text\" value=\""+_currPage+"\">";
				html +="<div class=\"div_span\">"+_langMap["i18n_page_y"]+"</div>";
				html +="<div class=\"div_span\">"+_langMap["i18n_page_g"]+"&nbsp;<span>"+_pageCnt+"</span>&nbsp;"+_langMap["i18n_page_y"]+"</div>";
				html +="<div class=\"span_blank\"></div>";
				html +="<div id=\"wd-tablediv_right\" class=\"czdiv div_right_active nextPage\"></div>";
				html +="<div id=\"wd-tablediv_rightall\" class=\"czdiv div_rightall_active bottomPage\"></div>";	
				html +="<div id=\"wd-tableselect\" class=\"div_selectbox\">";
				html +="<select class=\"rowList\">";
				$.each(_page.pageList,function(i,n){
					html +="<option value=\""+n+"\">"+n+"</option>";
				});
				html +="</select>";
				html +="</div>";
				html +="<div class=\"div_pagedetailbox\">";
				html +="<div class=\"div_span\">"+_langMap["i18n_page_dq"]+"&nbsp;<span id=\"wd-tablerowstart\">"+(_start+1)+"</span>&nbsp;-&nbsp;<span id=\"wd-tablerowend\">"+(_end+1)+"</span>&nbsp;"+_langMap["i18n_page_t"]+"</div>";
				html +="<div class=\"div_span\">"+_langMap["i18n_page_g"]+"&nbsp;<span id=\"wd-tablerecords\">"+_total+"</span>&nbsp;"+_langMap["i18n_page_t"]+"</div>";
				html +="</div>";
			    html +="</div>";
			_page.pageDiv.html(html);
			
			if(_currPage == 1){
				$(_page.pageDiv.find(".topPage")[0]).removeClass("div_fleft_all_active").addClass("div_fleft_all");
				$(_page.pageDiv.find(".prePage")[0]).removeClass("div_fleft_active").addClass("div_fleft");
			} 			
			if(_currPage == _pageCnt){
				$(_page.pageDiv.find(".bottomPage")[0]).removeClass("div_rightall_active").addClass("div_rightall");
				$(_page.pageDiv.find(".nextPage")[0]).removeClass("div_right_active").addClass("div_right");
			}	
			
			$(_page.pageDiv.find(".rowList")[0]).val(_page.count);
			_page.height = $("#"+_page.maskId)[0].clientHeight;
	        window.scrollTo(0,0);
	    },
	    bindLinks : function(){
	    	var _page = this;
	    	var _pageDiv = _page.pageDiv;
	    	_pageDiv.on("click",".topPage",function(){
	    		_page.top();
	    	});
	    	
			_pageDiv.on("click",".prePage",function(){
				_page.prev();
	    	});
			
			_pageDiv.on("click",".nextPage",function(){
				_page.next();   		
			});
			
			_pageDiv.on("click",".bottomPage",function(){
				_page.bottom();
			});
			
			_pageDiv.on("change",".rowList",function(){
				_page.changeRow($(this).val());
			});
			
			_pageDiv.on("keydown",".input_page",function(e){
				if (e.which == 13) {
					var reg = new RegExp('^(^[0-9]*[1-9][0-9]*$)*$');
					var pageIndex = 1;
					var _pageCnt = _page.msg.pageCnt;
					var _val = $(this).val();
					if (reg.test(_val) && _val.length > 0) {
						pageIndex = Number(_val);
						if(_val > _pageCnt){
							pageIndex = Number(_pageCnt);
						}
						_page.getByNum(pageIndex);
					} else {
						pageIndex = Number(_page.msg.currPage);
						$(".input_page").val(pageIndex);
					}
				}
			});
	    }
}



